package cn.laixueit.controller;

import cn.laixueit.entity.UserInfo;
import cn.laixueit.properties.JwtProperties;
import cn.laixueit.service.AuthService;
import cn.laixueit.utils.CookieUtils;
import cn.laixueit.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping
public class AuthController {


    @Autowired
    private AuthService authService;

    @Autowired
    JwtProperties jwtProperties;

    @GetMapping("/s")
    public ResponseEntity<String> s(){
        return  ResponseEntity.ok("ad");
    }

    @PostMapping("/login")
    public ResponseEntity<Void> login(@RequestParam("username")String username, @RequestParam("password")String password,
                                      HttpServletRequest request, HttpServletResponse response){
        // 登陆校验
        String tokeng =  authService.login(username,password);
        if(StringUtils.isBlank(tokeng)){
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        // 将token写入到cookie，并指定httpOnly为true，防止通过JS获取和修改
        CookieUtils.setCookie(request,response,jwtProperties.getCookieName(), tokeng, jwtProperties.getCookieMaxAge(),null,true);
        return  ResponseEntity.ok().build();
    }

    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("chuangmei-cookie")String token,HttpServletRequest request, HttpServletResponse response){
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());

            // 解析成功要重新刷新token
            token = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            // 更新cookie中的token
            // 将token写入到cookie，并指定httpOnly为true，防止通过JS获取和修改
            CookieUtils.setCookie(request,response,jwtProperties.getCookieName(), token, jwtProperties.getCookieMaxAge(),null,true);
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  ResponseEntity.status(HttpStatus.FOUND).build();
    }
}
